const DB = require('../init');
const {Sequelize,Op} = require('sequelize');
const fw = require('../../core/framework');

module.exports = {
    async create(data) {
        DB.ReportUserGroupDevice.sync();
        return await DB.ReportUserGroupDevice.create(data);
    },
    async delete(data) {
        return await DB.ReportUserGroupDevice.destroy({
            where: {
                id: data.id
            }
        });
    },
    async update(data) {
        return await DB.ReportUserGroupDevice.update(data, {
            where: {
                id: data.id
            }
        });
    },
    async search(data) {
        return await DB.ReportUserGroupDevice.findAll({
            where: data
        });
    },
    async searchAll(data){
        let currentPage = data.index || 0;
        let count = data.size || 10;
        let offset = currentPage * count;
        let query = {
            offset:offset,
            limit: parseInt(count),
            order: [
                ['created_at', 'desc'] // 按时间倒序，最新创建的在最上面。  正序是asc
            ],
            attributes: {
                exclude: ['createdAt', 'updatedAt'],
                include: [
                    [Sequelize.fn('date_format', Sequelize.col('created_at'), '%Y-%m-%d %H:%i:%s'), 'createtime'],
                    [Sequelize.fn('date_format', Sequelize.col('updated_at'), '%Y-%m-%d %H:%i:%s'), 'updatetime'],
                ]
            },
            // include:[{
            //     duplicating:false
            // }]
        };
        if(data.name){
            query.where = {
                name:{
                    [Op.like]:'%' + data.name + '%'
                }
            }
        }
        return await DB.ReportUserGroupDevice.findAndCountAll(query).then(res => {
            return fw.genPageData(data,res);
        });
    }
};
